#include "Log.hpp"
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <cstring>
#include <cstdlib>
#include <iostream>
using namespace LogModule;

// 给出 ip地址 端口号
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        std::cout << "Please use: " << argv[0] << " IP " << "PORT " << endl;
        exit(1);
    }

    uint32_t ip = inet_addr(argv[1]); // 注：字符串转合法ip地址
    uint16_t port = stoi(argv[2]);    // 注：字符串转整数

    // 创建套接字
    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd < 0)
    {
        LOG(LogLevel::FATAL) << "创建套接字失败";
        exit(1);
    }
    LOG(LogLevel::INFO) << "创建套接字";

    // 绑定？不用显示绑定,OS会自动的绑定
    // 填写服务器信息
    struct sockaddr_in local;
    memset(&local, 0, sizeof(local));
    local.sin_family = AF_INET;
    local.sin_addr.s_addr = ip;
    local.sin_port = htons(port);

    // 一定是死循环
    while (true)
    {
        // 向服务器发送信息
        cout << "Please Cin # ";
        std::string buff;
        cin >> buff;
        // std::getline(std::cin, buff);
        // buff.size()-1 会丢失最后一个字符，应改为 buff.size()
        ssize_t s = sendto(sockfd, buff.c_str(), buff.size(), 0, (struct sockaddr *)&local, sizeof(local));
        if (s < 0)
        {
            LOG(LogLevel::WARNING) << "向服务器发送信息失败";
            exit(1);
        }

        // 接收服务器返回的信息
        char buffer[1024];
        memset(&buffer, 0, sizeof(buffer));
        struct sockaddr_in peer;
        socklen_t len = sizeof(peer);
        ssize_t ss = recvfrom(sockfd, buffer, sizeof(buffer), 0, (struct sockaddr *)&peer, &len);
        if (ss < 0)
        {
            LOG(LogLevel::WARNING) << "接收服务器信息失败";
            exit(1);
        }
        printf("%s\n", buffer);
        memset(&buff, 0, sizeof(buffer)); // 清理缓存
    }
}